package com.eryos.gwt.mailmodule.server;

import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Message;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import com.eryos.gwt.mailmodule.client.MailService;
import com.eryos.gwt.mailmodule.shared.CaptchaCheck;
import com.eryos.gwt.mailmodule.shared.MailMessage;
import com.eryos.gwt.mailmodule.shared.exception.InvalidCaptchaException;
import com.eryos.gwt.mailmodule.shared.exception.InvalidMailException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class MailServiceImpl extends RemoteServiceServlet implements MailService {

	private static final String PRIVATE_KEY 		= "6Ld5OskSAAAAAEVV8jmQJkezi9XpAgEMQShM8UqS";
	private static final String RECIPIENT_ADDRESS 	= "combe.olivier@gmail.com";
	private static final String RECIPIENT_NAME 		= "GAE Mail Service";

	/**
	 * 
	 */
	public Boolean sendMailWithCaptcha(MailMessage _msg, CaptchaCheck captcha) throws InvalidCaptchaException, InvalidMailException {

		// Test Captcha Challenge VS response
		boolean captchaResult = checkCaptach(captcha.getChallenge(), captcha.getResponse());

		// Check Captcha return
		if (! captchaResult )
			throw new InvalidCaptchaException("Captcha is not correct");

		// Check Mail address
		if (_msg.getSender().getMailAddress() == null) 
			throw new InvalidMailException("To field cannot be empty.");

		try {

			//Call the GAEJ Email Service
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);

			// Define Recipient & Sender
			InternetAddress sender = new InternetAddress(_msg.getSender().getMailAddress());
			sender.setPersonal(_msg.getSender().getLastName());

			InternetAddress recipient = new InternetAddress(RECIPIENT_ADDRESS);
			sender.setPersonal(RECIPIENT_NAME);

			// Create message
			Message msg = new MimeMessage(session);
			msg.setFrom(sender);
			msg.addRecipient(Message.RecipientType.TO, recipient);			
			msg.setSubject(_msg.getSubject());
			msg.setText(_msg.getMessage());

			// Send Message
			Transport.send(msg);

		} catch (Exception ex) {
			return false;
		}

		return true;
	}


	/**
	 * 
	 * @param _challenge
	 * @param _response
	 * @return
	 * @throws IllegalArgumentException
	 */
	private boolean checkCaptach(String _challenge, String _response) throws IllegalArgumentException{

		String challenge = _challenge; //(String) req.getParameter("recaptcha_challenge_field");
		String response = _response;//(String) req.getParameter("recaptcha_response_field");

		if ((challenge == null) || (response == null)) {
			throw new IllegalArgumentException("Your words did not match. Please try submitting again.");
			//throw new Exception("Your words did not match. Please try submitting again.");
		}

		String remoteAddr = getThreadLocalRequest().getRemoteHost(); // localhost // req.getRemoteAddr();

		ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
		reCaptcha.setPrivateKey(PRIVATE_KEY);

		ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, response);

		if (!reCaptchaResponse.isValid())
			return false;

		return true;
	}
}
